package com.mooer.app;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.mooer.R;
import com.mooer.bean.SignInfo;
import com.mooer.exception.SVException;
import com.mooer.http.HttpUtils;
import com.mooer.utils.ui.ProgressLinearLayout;

public class SignMeList extends Activity implements OnClickListener {

	private TextView number;

	private ListView listView;

	private ProgressLinearLayout footer;

	private SimpleAdapter adapter;

	private List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.sign_me_list);
		Intent intent = getIntent();
		number = (TextView) findViewById(R.id.sign_num);
		listView = (ListView) findViewById(R.id.listview);
		footer = (ProgressLinearLayout) LayoutInflater.from(this).inflate(
				R.layout.progress_small, null);
		footer.initView();
		listView.addFooterView(footer);
		adapter = new SimpleAdapter(this, list, R.layout.sign_item,
				new String[] { "name", "date" }, new int[] { R.id.name,
						R.id.date });
		listView.setAdapter(adapter);

		number.setText(getString(R.string.sign_num,
				intent.getIntExtra("number",0)));
		footer.setOnClickListener(this);

		new SignListTask().execute(intent.getIntExtra("id", 0));
	}

	private class SignListTask extends
			AsyncTask<Integer, Integer, List<SignInfo>> {

		private boolean isException;

		@Override
		protected List<SignInfo> doInBackground(Integer... params) {
			List<SignInfo> list = null;
			try {
				list = HttpUtils
						.fetchHisSignedShopListByUser(params[0], 0, 100);
			} catch (Exception e) {
				isException = true;
				e.printStackTrace();
			}

			return list;
		}

		@Override
		protected void onPostExecute(List<SignInfo> result) {
			super.onPostExecute(result);
			if (isException) {
				footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
						View.VISIBLE);
			} else {
				if (result.size() > 0) {
					for (SignInfo signInfo : result) {
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("name", signInfo.getShop().getName());
						map.put("date", signInfo.getDate());
						list.add(map);
					}
					listView.removeFooterView(footer);
					adapter.notifyDataSetChanged();
				} else {
					footer.setVisibility(View.GONE, View.GONE, View.VISIBLE,
							View.GONE);
					footer.setText(null, "您暂无签到记录");
				}
			}
		}

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub

	}

}
